<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('workorder.orders.quick Search Fields') })"
        ></TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef">
            <template #engineerTitles>
                <el-table-column align="center" label="工程师">
                    <template #default="{ row }">
                        <el-tag class="engineer-tags" v-for="(item, idx) in row.engineers" :key="idx">{{ item.title }}</el-tag>
                    </template>
                </el-table-column>
            </template>
            <template #processTitles>
                <el-table-column align="center" label="当前状态">
                    <template #default="{ row }">
                        <el-tag class="engineer-tags" v-for="(item, idx) in row.process_text" :key="idx">{{ item }}</el-tag>
                    </template>
                </el-table-column>
            </template>
            <template #caseDetail>
                <el-table-column align="center" label="案件详情">
                    <template #default="{ row }">
                        <el-tag class="engineer-tags" @click="infoButtonClick(row)">查看</el-tag>
                        <!--                        <el-tag class="engineer-tags" v-for="(item, idx) in row.process_text" :key="idx">{{ item }}</el-tag>-->
                    </template>
                </el-table-column>
            </template>
            <template #openReport>
                <el-table-column align="center" label="初步分析">
                    <template #default="{ row }">
                        <el-tag class="engineer-tags" @click="lookReport(row)" v-if="row.open_report !== '待审核'">{{ row.open_report }}</el-tag>
                        <el-tag class="engineer-tags" @click="lookReport(row)" v-if="row.open_report === '待审核'" style="color: red">{{
                            row.open_report
                        }}</el-tag>
                        <el-tag class="engineer-tags" v-show="row.report_status == 1">{{ row.have_report }}</el-tag>
                        <el-tag class="engineer-tags" v-show="row.open_level">优先级:{{ row.open_level }}</el-tag>
                    </template>
                </el-table-column>
            </template>
            <template #deepReport>
                <el-table-column align="center" label="深入分析">
                    <template #default="{ row }">
                        <el-tag class="engineer-tags" @click="lookDeepReport(row)" v-show="row.deep_report !== ''">{{ row.deep_report }}</el-tag>
                        <el-tag class="engineer-tags" v-show="row.deep_status == 1">{{ row.have_deep_report }}</el-tag>
                        <el-tag class="engineer-tags" v-show="row.deep_level">优先级:{{ row.deep_level }}</el-tag>
                    </template>
                </el-table-column>
            </template>
        </Table>

        <el-dialog class="ba-operate-dialog select-db-dialog" v-model="state.dialog.visible" title="指派工程师" :destroy-on-close="true">
            <el-form @keyup.enter="onSubmit()" class="select-db-form" ref="formRef">
                <el-select v-model="value1" multiple placeholder="选择工程师" style="width: 240px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select v-model="value2" placeholder="初步分析优先级" style="width: 240px">
                    <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select v-model="value3" placeholder="深入分析优先级" style="width: 240px">
                    <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>

                <!--                    <FormItem-->
                <!--                        label="工程师"-->
                <!--                        class="select-db"-->
                <!--                        type="select"-->
                <!--                        :key="JSON.stringify(state.dialog.dbList)"-->
                <!--                        v-model="state.dialog.workerId"-->
                <!--                        placeholder="选择工程师"-->
                <!--                        :data="{-->
                <!--                            content: state.dialog.dbList,-->
                <!--                        }"-->
                <!--                        :attr="{-->
                <!--                            blockHelp: '这里只能指派内部工程师进行处理',-->
                <!--                        }"-->
                <!--                        prop="workerId"-->
                <!--                    />-->
            </el-form>
            <template #footer>
                <div :style="{ width: 'calc(100% * 0.9)' }">
                    <el-button @click="state.dialog.visible = false">{{ $t('Cancel') }}</el-button>
                    <el-button :loading="state.loading" @click="onSubmit()" v-blur type="primary">{{ t('Confirm') }}</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 报告表单 -->
        <el-dialog class="ba-operate-dialog" v-model="state.report.visible">
            <template #header>
                <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">{{ t('Info') }}</div>
            </template>
            <el-scrollbar v-loading="state.report.loading" class="ba-table-form-scrollbar">
                <div class="ba-operate-form">
                    <el-descriptions :column="2" border>
                        <el-descriptions-item label="审核状态">
                            {{ getStatusText(state.report!.info.status) }}
                        </el-descriptions-item>
                        <el-descriptions-item label="提交时间">
                            {{ timeFormat(state.report!.info.create_time) }}
                        </el-descriptions-item>
                        <el-descriptions-item :width="120" :span="2" label="案件名称">
                            {{ state.report.info.title }}
                        </el-descriptions-item>
                        <el-descriptions-item :width="120" :span="2" label="报告文件">
                            <!--                            <el-button type="primary" size="small" v-if="state.report!.info.file" @click="onDownload(state.report!.info.file)">-->
                            <!--                                点击下载 {{ getFileSuffix(state.report!.info.file) }} 文件-->
                            <!--                            </el-button>-->
                            <el-button
                                type="primary"
                                size="small"
                                v-if="state.report!.info.file"
                                @click="onDownload(item)"
                                v-for="(item, idx) in state.report!.info.file"
                                :key="idx"
                            >
                                点击下载 {{ getFileSuffix(item) }} 文件
                            </el-button>
                        </el-descriptions-item>
                        <el-descriptions-item :width="140" :span="2" label="案件下一步状态">
                            {{ state.report!.info.process_text }}
                        </el-descriptions-item>
                        <el-descriptions-item :width="120" :span="2" label="初步分析结果">
                            {{ state.report!.info.remark }}
                        </el-descriptions-item>
                    </el-descriptions>
                    <div style="margin-top: 10px; position: absolute">
                        <el-input
                            v-model="state.report.info.reject_content"
                            maxlength="50"
                            style="width: 240px"
                            placeholder="请输入审核意见"
                            show-word-limit
                            type="textarea"
                        />
                    </div>
                </div>
            </el-scrollbar>
            <template #footer>
                <div :style="'width: calc(100% - 20px)'">
                    <el-button @click="closeReport">{{ t('Cancel') }}</el-button>
                    <el-button
                        v-blur
                        :loading="state.report.loading"
                        @click="onSubmitCheck(1)"
                        type="primary"
                        v-show="state.report!.info.status !== 1"
                    >
                        通过
                    </el-button>
                    <el-button
                        v-blur
                        :loading="state.report.loading"
                        @click="onSubmitCheck(4)"
                        type="primary"
                        v-show="state.report!.info.status !== 1"
                    >
                        驳回
                    </el-button>
                    <!--                    <el-button v-else v-blur type="primary" disabled>-->
                    <!--                        已审核-->
                    <!--                    </el-button>-->
                </div>
            </template>
        </el-dialog>
        <!-- 深入报告表单 -->
        <el-dialog class="ba-operate-dialog" v-model="state.deepReport.visible">
            <template #header>
                <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">{{ t('Info') }}</div>
            </template>
            <el-scrollbar v-loading="state.deepReport.loading" class="ba-table-form-scrollbar">
                <div class="ba-operate-form">
                    <el-descriptions :column="2" border>
                        <el-descriptions-item label="审核状态">
                            {{ getStatusText(state.deepReport!.info.status) }}
                        </el-descriptions-item>
                        <el-descriptions-item label="提交时间">
                            {{ timeFormat(state.deepReport!.info.create_time) }}
                        </el-descriptions-item>
                        <el-descriptions-item :width="120" :span="2" label="案件名称">
                            {{ state.deepReport.info.title }}
                        </el-descriptions-item>
                        <el-descriptions-item :width="120" :span="2" label="报告文件">
                            <!--                            <el-button type="primary" size="small" v-if="state.report!.info.file" @click="onDownload(state.report!.info.file)">-->
                            <!--                                点击下载 {{ getFileSuffix(state.report!.info.file) }} 文件-->
                            <!--                            </el-button>-->
                            <el-button
                                type="primary"
                                size="small"
                                v-if="state.deepReport!.info.file"
                                @click="onDownload(item)"
                                v-for="(item, idx) in state.deepReport!.info.file"
                                :key="idx"
                            >
                                点击下载 {{ getFileSuffix(item) }} 文件
                            </el-button>
                        </el-descriptions-item>
                        <el-descriptions-item :width="140" :span="2" label="案件下一步状态">
                            {{ state.deepReport!.info.process_text }}
                        </el-descriptions-item>
                        <el-descriptions-item :width="120" :span="2" label="初步分析结果">
                            {{ state.deepReport!.info.remark }}
                        </el-descriptions-item>
                    </el-descriptions>
                    <div style="margin-top: 10px; position: absolute">
                        <el-input
                            v-model="state.deepReport.info.reject_content"
                            maxlength="50"
                            style="width: 240px"
                            placeholder="请输入审核意见"
                            show-word-limit
                            type="textarea"
                        />
                    </div>
                </div>
            </el-scrollbar>
            <template #footer>
                <div :style="'width: calc(100% - 20px)'">
                    <el-button @click="closeReport">{{ t('Cancel') }}</el-button>
                    <el-button
                        v-blur
                        :loading="state.deepReport.loading"
                        @click="onSubmitDeepCheck(1)"
                        type="primary"
                        v-show="state.deepReport!.info.status !== 1"
                    >
                        通过
                    </el-button>
                    <el-button
                        v-blur
                        :loading="state.deepReport.loading"
                        @click="onSubmitDeepCheck(4)"
                        type="primary"
                        v-show="state.deepReport!.info.status !== 1"
                    >
                        驳回
                    </el-button>
                    <!--                    <el-button v-else v-blur type="primary" disabled>-->
                    <!--                        已审核-->
                    <!--                    </el-button>-->
                </div>
            </template>
        </el-dialog>
        <!-- 表单 -->
        <PopupForm />

        <Records />

        <Info />
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import Records from './records.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import { buildValidatorData, buildValidatorParams } from '/@/utils/validate'
import { isEmpty, concat, cloneDeep } from 'lodash-es'
import { buildJsonToElTreeData, fullUrl, timeFormat } from '/@/utils/common'
import { getWorkerList, assign, getFieldConfig, getReport, checkReport, getDeepReport, checkDeepReport } from '/@/api/backend/workorder'
import FormItem from '/@/components/formItem/index.vue'
import Info from './info.vue'
import { ElMessage } from 'element-plus'
defineOptions({
    name: 'workorder/orders',
})
const getFileSuffix = (filePath: string) => {
    if (filePath) {
        const arr = filePath.split('.')
        return arr[arr.length - 1]
    }
    return '未知'
}
const onSubmitCheck = (status) => {
    // state.dialog.loading = true
    if (state.report.info.reject_content === '') {
        return ElMessage({
            message: '请输入审核意见',
            type: 'warning',
        })
    }
    state.report.visible = false
    checkReport({
        id: state.report.info.id,
        ispass: status,
        reject_content: state.report.info.reject_content,
    })
        .then(() => {
            //baTable.toggleForm
        })
        .finally
        // location.reload()
        ()
}
const onSubmitDeepCheck = (status) => {
    // state.dialog.loading = true
    if (state.deepReport.info.reject_content === '') {
        return ElMessage({
            message: '请输入审核意见',
            type: 'warning',
        })
    }
    state.deepReport.visible = false
    checkDeepReport({
        id: state.deepReport.info.id,
        ispass: status,
        reject_content: state.deepReport.info.reject_content,
    })
        .then(() => {
            //baTable.toggleForm
        })
        .finally
        // location.reload()
        ()
}
const onDownload = (url: string) => {
    if (url) {
        const a = document.createElement('a')
        a.href = fullUrl(url)
        a.download = ''
        a.target = '_blank'
        a.click()
    }
}
const getStatusText = (status: number) => {
    // 0待发送，1已接收，2进行中，3挂起，4结束，5取消
    switch (status) {
        case 0:
            return '待审核'
        case 1:
            return '审核通过'
        case 2:
            return '已生成'
        case 3:
            return '已发送'
        case 4:
            return '驳回'
        default:
            return '未知'
    }
}
const radio = ref(1)
const state = reactive({
    dialog: {
        clueId: 0,
        workerId: 0,
        visible: false,
        dbList: [],
        loading: false,
    },
    showLog: false,
    loading: false,
    successRecord: 0,
    report: {
        visible: false,
        loading: false,
        info: [],
    },
    deepReport: {
        visible: false,
        loading: false,
        info: [],
    },
})
const value1 = ref([])
const value2 = ref([])
const value3 = ref([])
const options = ref([])
const options1 = [
    {
        value: '1',
        label: '普通',
    },
    {
        value: '2',
        label: '中等',
    },
    {
        value: '3',
        label: '高级',
    },
]
const { t } = useI18n()
const tableRef = ref()
let optButtons: OptButton[] = [
    // {
    //     render: 'tipButton',
    //     name: 'info',
    //     title: 'Info',
    //     text: '',
    //     type: 'primary',
    //     icon: 'fa fa-search-plus',
    //     class: 'table-row-edit',
    //     disabledTip: false,
    //     click: (row: TableRow) => {
    //         infoButtonClick(row)
    //     },
    // },
    {
        render: 'tipButton',
        name: 'info',
        title: '指派工程师',
        text: '',
        type: 'primary',
        icon: 'fa fa-check icon',
        class: 'table-row-edit',
        disabledTip: false,
        click: (row: TableRow) => {
            assignButtonClick(row)
        },
    },
    {
        render: 'tipButton',
        name: 'history',
        title: 'workorder.orders.records',
        type: 'success',
        icon: 'fa fa-file-text-o',
        disabledTip: false,
        click(row) {
            baTable.table.extend!.infoId = row.id
        },
    },
]
optButtons = optButtons.concat(defaultOptButtons(['edit', 'delete']))

const { data } = await getFieldConfig()

// 动态字段
let rules: anyObj = {}
let defaultItems: anyObj = {}
//const dynamicColumns: TableColumn[] = []

// 字段配置
const columnData: TableColumn[] = [
    { type: 'selection', align: 'center', operator: false },
    { label: t('workorder.orders.id'), prop: 'id', align: 'center', width: 70, operator: false, sortable: 'custom' },
    {
        label: '提交时间',
        prop: 'create_time',
        align: 'center',
        render: 'datetime',
        operator: 'RANGE',
        sortable: 'custom',
        width: 190,
        timeFormat: 'yyyy年mm月dd时hh分ss秒',
    },
    {
        label: '案件名称',
        prop: 'title',
        align: 'center',
        operatorPlaceholder: t('Fuzzy query'),
        operator: 'LIKE',
        sortable: false,
    },
    {
        label: '案件类型',
        prop: 'category_name',
        align: 'center',
        operatorPlaceholder: t('Fuzzy query'),
        //render: 'tags',
        operator: false,
    },
    {
        label: '重要程度',
        render: 'tag',
        align: 'center',
        prop: 'urgent_rank_name',
        operator: false,
    },
    {
        label: '诈骗金额',
        prop: 'money',
        align: 'center',
        operatorPlaceholder: t('Fuzzy query'),
        //render: 'tags',
        operator: false,
    },
    {
        label: '单位',
        prop: 'company.name',
        align: 'center',
        operatorPlaceholder: t('Fuzzy query'),
        //render: 'tags',
        operator: false,
    },
    {
        label: '单位',
        prop: 'company.id',
        align: 'center',
        render: 'tag',
        show: false,
        renderFormatter: (row: TableRow) => {
            return row.company.name
        },
        comSearchRender: 'remoteSelect',
        remote: {
            pk: 'id',
            field: 'name',
            remoteUrl: '/admin/Company/' + 'index',
        },
    },
    {
        label: '案件类型',
        prop: 'category_id',
        align: 'center',
        render: 'tag',
        show: false,
        renderFormatter: (row: TableRow) => {
            return row.name
        },
        comSearchRender: 'remoteSelect',
        remote: {
            pk: 'id',
            field: 'name',
            remoteUrl: '/admin/workorder.Category/' + 'index',
        },
    },
    {
        label: t('workorder.orders.engineers__title'),
        render: 'slot',
        slotName: 'engineerTitles',
        operator: false,
    },
    {
        label: t('workorder.orders.engineers__title'),
        prop: 'engineers',
        align: 'center',
        operator: 'FIND_IN_SET',
        show: false,
        // renderFormatter: (row: TableRow) => {
        //     return row.name
        // },
        comSearchRender: 'remoteSelect',
        remote: { pk: 'engineers.id', field: 'title', remoteUrl: '/admin/workorder.Engineers/index', multiple: true },
    },
    {
        label: '当前状态',
        render: 'slot',
        slotName: 'processTitles',
        operator: false,
    },
    {
        label: '案件详情',
        render: 'slot',
        slotName: 'caseDetail',
        operator: false,
    },
    {
        label: '初步分析',
        render: 'slot',
        slotName: 'openReport',
        operator: false,
    },
    {
        label: '深入分析',
        render: 'slot',
        slotName: 'deepReport',
        operator: false,
    },
    {
        label: '当前状态',
        prop: 'tag_id',
        align: 'center',
        render: 'tag',
        show: false,
        renderFormatter: (row: TableRow) => {
            return row.name
        },
        comSearchRender: 'remoteSelect',
        remote: {
            pk: 'id',
            field: 'name',
            remoteUrl: '/admin/workorder.Orders/' + 'sysTags',
        },
    },
    {
        label: '诈骗金额',
        prop: 'money_id',
        align: 'center',
        render: 'tag',
        show: false,
        renderFormatter: (row: TableRow) => {
            return row.name
        },
        comSearchRender: 'remoteSelect',
        remote: {
            pk: 'id',
            field: 'name',
            remoteUrl: '/admin/workorder.Orders/' + 'moneyList',
        },
    },

    // {
    //     label: '报告数量',
    //     prop: 'report_count',
    //     align: 'center',
    //     operator: false,
    //     sortable: false,
    // },

    {
        show: false,
        label: '案件状态',
        prop: 'status',
        align: 'center',
        render: 'tag',
        operator: 'eq',
        sortable: false,
        custom: { pending: 'danger', received: 'danger', dealing: 'danger', paused: 'success', done: 'success', canceled: 'success' },
        replaceValue: { pending: '待发送', received: '已接收', dealing: '进行中', paused: '挂起', done: '结束', canceled: '取消' },
    },
    {
        show: false,
        label: '重要程度',
        prop: 'urgent_rank_id',
        align: 'center',
        render: 'tag',
        operator: 'eq',
        sortable: false,
        custom: { '1': '普通', '2': '中等', '3': '高级' },
        replaceValue: { '1': '普通', '2': '中等', '3': '高级' },
    },
    { label: t('Operate'), align: 'center', width: 150, render: 'buttons', buttons: optButtons, operator: false },
]
//columnData.splice(10, 0, ...dynamicColumns)

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/workorder.Orders/'),
    {
        pk: 'id',
        column: columnData,
        dblClickNotEditColumn: ['all'], //undefined
    },
    {
        defaultItems: { status: 'pending', last_urging_time: null, ...defaultItems },
    }
)

baTable.form.extend!.rules = rules
baTable.table.extend!.fieldConfig = data

provide('baTable', baTable)

/** 点击查看详情按钮响应 */
const infoButtonClick = (row: TableRow) => {
    if (!row) return
    // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
    let rowClone = cloneDeep(row)
    rowClone.data1 = rowClone.data1 ? [{ label: '点击展开', children: buildJsonToElTreeData(JSON.parse(rowClone.data1)) }] : []
    rowClone.data2 = rowClone.data2 ? [{ label: '点击展开', children: buildJsonToElTreeData(JSON.parse(rowClone.data2)) }] : []
    rowClone.data3 = rowClone.data3 ? [{ label: '点击展开', children: buildJsonToElTreeData(JSON.parse(rowClone.data3)) }] : []
    baTable.form.extend!['info'] = rowClone
    baTable.form.operate = 'Info'
}

/** 点击指派按钮响应 */
const assignButtonClick = (row: TableRow) => {
    value1.value = []
    value2.value = ''
    value3.value = ''
    if (!row) return
    // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
    state.successRecord = 1
    state.dialog.clueId = row.id
    getWorkerList().then((res) => {
        console.log(res.data, options, res)
        // state.dialog.dbList = res.data
        // options.value = res.data.list
        for (let i = 0; i < res.data.list.length; i++) {
            options.value.push({ value: res.data.list[i].id, label: res.data.list[i].title })
        }
        state.dialog.visible = true
    })
}
const closeReport = () => {
    state.report.visible = false
    state.report.info = []
}
const closeDeepReport = () => {
    state.deepReport.visible = false
    state.deepReport.info = []
}
const lookReport = (row) => {
    if (row.open_report === '初步分析中' || row.open_report === '待指派') {
        return
    }
    state.report.visible = true
    getReport({
        wo_id: row.id,
    })
        .then((res) => {
            state.report.info = res.data.info
        })
        .finally(() => {
            state.report.loading = false
        })
}
const lookDeepReport = (row) => {
    if (row.deep_report === '深入分析中' || row.deep_report === '待指派') {
        return
    }
    state.deepReport.visible = true
    getDeepReport({
        wo_id: row.id,
    })
        .then((res) => {
            state.deepReport.info = res.data.info
        })
        .finally(() => {
            state.deepReport.loading = false
        })
}
// 提交指派工程师
const onSubmit = () => {
    state.dialog.loading = true
    assign({
        id: state.dialog.clueId,
        engineer: value1.value,
        open_level: value2.value,
        deep_level: value3.value,
    })
        .then(() => {
            state.dialog.visible = false
            baTable.getIndex()
        })
        .finally(() => {
            state.dialog.loading = false
        })
}

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss">
:deep(.select-db-dialog) .el-dialog__body {
    height: unset;
    .select-db-form {
        width: 88%;
        text-align: center;
        height: auto;
    }
    .success-record-alert {
        width: calc(100% - 140px);
        margin-left: 140px;
        margin-bottom: 30px;
        margin-top: -30px;
    }
}
.engineer-tags {
    margin-top: 4px;
}
.select-db {
    margin: 40px 0;
}
</style>
